import axios from 'axios';
import QS from 'qs';
import * as storage from '@/utils/localStorageUtil';

// 环境的切换
axios.defaults.baseURL = process.env.API_ROOT;
// 请求超时时间
axios.defaults.timeout = 10000;
// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
axios.defaults.headers.post['language'] = localStorage.getItem('lang') || 'zh';
// get请求头
axios.defaults.headers.get['language'] = localStorage.getItem('lang') || 'zh';

/** 
 * get方法，对应get请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
 export function get(url, params,toLogin = true){    
  return new Promise((resolve, reject) =>{        
      axios.get(url, {            
        params: params,
        headers:{
          'Authorization':storage.getLocalStorage('francis:jwt')
        }
      })        
      .then(res => { 
        if(res.data.code == 401){
          if(toLogin){
            location.href = '/admin'; 
          }
        }  
        resolve(res.data);        
      })        
      .catch(err => {            
          reject(err.data)        
      })    
  });
}

/** 
* post方法，对应post请求 
* @param {String} url [请求的url地址] 
* @param {Object} params [请求时携带的参数] 
* @param {Object} options [请求时的选项，如headers等] 
*/
export function post(url, params, options = {},toLogin = true) {    
    return new Promise((resolve, reject) => {   
      const headers = Object.assign({            
        'Authorization':storage.getLocalStorage('francis:jwt')
      }, options.headers || {});  
      axios.post(url, params, {
          headers
      })        
      .then(res => {       
        if(res.data.code == 401){
          if(toLogin){
            location.href = '/admin'; 
          }
        }   
        resolve(res.data);        
      })        
      .catch(err => {            
        reject(err.data)        
      })    
    });
}

/**
 * 获取基础api请求地址
 */
export function getBaseUrl(){
    return process.env.API_ROOT ;
}
